﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Furion;
using Furion.DynamicApiController;
using Furion.UnifyResult;
using ADSTS_SERVER.Models;
using ADSTS_SERVER.ViewModels.Project;
using ADSTS_SERVER.ViewModels.Robot;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;

namespace ADSTS_SERVER.Controllers
{
    /// <summary>
    /// 工程
    /// </summary>
    [DynamicApiController]
    public class LnsProjectController
    {
        private readonly ILogger<LnsProjectController> logger;
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public LnsProjectController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
            this.logger = logger;
        }

        /// <summary>
        /// 工程列表
        /// </summary>
        /// <param name="psf"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> List([FromBody] ProjectSearchForm psf)
        {
            RefAsync<int> total = 0;
            List<Project> projects = await db.Queryable<Project>()
                .Mapper(pj => pj.User, pj => pj.UId, pj => pj.User.Id)
                .Mapper(pj => pj.MapModel, pj => pj.MapId, pj => pj.MapModel.Id)
                .Mapper(pj => pj.Robot, pj => pj.RbtId, pj => pj.Robot.Id)
                .Mapper(pj => pj.TestUseCase, pj => pj.TUCId, pj => pj.TestUseCase.Id)
                .Mapper(pj => pj.ProjectTestResults, pj => pj.ProjectTestResults.FirstOrDefault().PjId)
                .Mapper(pj => pj.Cluster, pj => pj.CluId, pj => pj.Cluster.Id)
                .Where(pj => pj.IsActive == 1)
                .WhereIF(!string.IsNullOrEmpty(psf.Content), pj => pj.Name.Contains(psf.Content) || pj.Description.Contains(psf.Content))
                .WhereIF(psf.UId != 0, pj => pj.UId == psf.UId)
                .ToPageListAsync(psf.PageIndex, psf.PageSize, total);

            UnifyContext.Fill(new { Total = total.Value });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = projects,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 增加工程
        /// </summary>
        /// <param name="psf"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Save([FromBody] ProjectSaveForm vo)
        {
            vo.FullDateTime = DateTime.Parse($"{vo.Pdate} {vo.Ptime}");
            vo.SerialNo = DateTime.Now.ToString("yyyyMMddHHmmss");
            await db.Insertable<Project>(vo.Adapt<Project>()).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = vo,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 删除工程
        /// </summary>
        /// <param name="pdf"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Delete([FromBody] ProjectDeleteForm pdf) {
            await db.Updateable<Project>(new Project { IsActive = 0 }).UpdateColumns(pj => pj.IsActive).Where(pj => pj.Id == pdf.Id).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 修改工程
        /// </summary>
        /// <param name="vo"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Update([FromBody] ProjectUpdateForm vo) {
            vo.FullDateTime = DateTime.Parse($"{vo.Pdate} {vo.Ptime}");
            await db.Updateable<Project>(vo).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = vo,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 查看工程
        /// </summary>
        /// <param name="psf"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Show([FromBody] ProjectShowForm psf) {
            Project project = await db.Queryable<Project>()
                .Mapper(pj => pj.User, pj => pj.UId, pj => pj.User.Id)
                .Mapper(pj => pj.MapModel, pj => pj.MapId, pj => pj.MapModel.Id)
                .Mapper(pj => pj.Robot, pj => pj.RbtId, pj => pj.Robot.Id)
                .Mapper(pj => pj.TestUseCase, pj => pj.TUCId, pj => pj.TestUseCase.Id)
                .Mapper(pj => pj.ProjectTestResults, pj => pj.ProjectTestResults.FirstOrDefault().PjId)
                .Mapper(pj => pj.Cluster, pj => pj.CluId, pj => pj.Cluster.Id)
                .InSingleAsync(psf.Id);
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = project,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

    }
}
